
import moment from 'moment'

export function toBase64(value) {
  if (window.btoa) {
    return window.btoa(value)
  }
  return value
}

export function fromBase64(value) {
  if (window.atob) {
    return window.atob(value)
  }
  return value
}

export function toBase64X(value, salt) {
  const value0 = randomString(10) + moment(new Date()).format('YYYYMMDDHHmmssSSS') + value + salt
  return toBase64(value0)
}

export function fromBase64X(value, length) {
  const value0 = fromBase64(value)
  // console.log(value0, 'hihi')
  if (value0 && value0.length > 27) {
    return value0.substring(27, 27 + length)
  }
  return value
}

export function randomString(length) {
  let str = Math.random().toString(36).substring(2)
  if (str.length >= length) {
    return str.substring(0, length)
  }
  str += randomString(length - str.length)
  return str
}
export function base64ConvertFile(urlData, filename) {
  // 64转file
  if (typeof urlData != 'string') {
    this.$toast('urlData不是字符串')
    return
  }
  var arr = urlData.split(',')
  var type = arr[0].match(/:(.*?);/)[1]
  var fileExt = type.split('/')[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], 'filename.' + fileExt, {
    type: type
  })
}
